package gov.kqqzyyy.monkey.orderpad.mytools;

import android.util.Log;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Monkey on 2017/9/26.
 * XML转对象解析类
 */

public class XMLUtils {

    //返回结果为列表
    public static <T> List<T> readXMLList(String XMLString, Class<?> cls) {
        List<T> list = new ArrayList<>();//创建list集合
        try {
            T t = (T) cls.newInstance();
            Field[] field = t.getClass().getDeclaredFields();// 获取实体类的所有属性，返回Field数组
            Document document = DocumentHelper.parseText(XMLString);//将字符串转化为xml
            Element rootElement = document.getRootElement();//获得根节点
            for (Iterator it = rootElement.elementIterator(); it.hasNext(); ) {// 遍历
                Element e = (Element) it.next();// 获取某个子节点对象
                t = (T) cls.newInstance();//获取实体类实例
                for (Field aField : field) {
                    String name = aField.getName();// 获取属性的名字
                    name = name.substring(0, 1).toUpperCase() + name.substring(1);//将第一位转化为大写，便于获取实体类中set,get方法
                    Method m = t.getClass().getMethod("set" + name, String.class);//获得set方法
                    m.invoke(t, e.elementText(aField.getName().toUpperCase()));        //e.elementText元素的某个指定的子元素中的text信息
                }
                list.add(t);
            }
        } catch (Exception e) {
            Log.d("APE", "readXMLList: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return list;
    }

    public static <T> T readXML(String XMLString, Class<?> cls) {
        try {
            T t = (T) cls.newInstance();
            Document document = DocumentHelper.parseText(XMLString);//将字符串转化为xml
            Element rootElement = document.getRootElement();//获得根节点
            for (Iterator it = rootElement.elementIterator(); it.hasNext(); ) {
                Element element = (Element) it.next();
                String elementName = element.getName();
                String elementValue = element.getText();
                elementName = elementName.substring(0, 1).toUpperCase() + elementName.substring(1);
                Method method = t.getClass().getMethod("set" + elementName, String.class);
                method.invoke(t, elementValue);
            }
            return t;
        } catch (Exception e) {
            Log.d("APE", "readXML: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }
}

